package cn.com.ddapp.ddm.ui.mine;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.ypy.eventbus.EventBus;
import com.zhy.autolayout.AutoRelativeLayout;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import cn.com.ddapp.ddm.AppConfig;
import cn.com.ddapp.ddm.R;
import cn.com.ddapp.ddm.api.OKUtilAPI;
import cn.com.ddapp.ddm.base.BaseActivity;
import cn.com.ddapp.ddm.base.BaseApplication;
import cn.com.ddapp.ddm.bean.Entity;
import cn.com.ddapp.ddm.bean.mine.AllCard;
import cn.com.ddapp.ddm.bean.mine.BindSettingActivity;
import cn.com.ddapp.ddm.bean.mine.DefaultBank;
import cn.com.ddapp.ddm.bean.mine.UserData;
import cn.com.ddapp.ddm.inter.OkUtilCallback;
import cn.com.ddapp.ddm.ui.empty.EmptyLayout;
import cn.com.ddapp.ddm.util.NetUtils;
import cn.com.ddapp.ddm.util.SPUtils;
import cn.com.ddapp.ddm.widget.PayPwdEditText;

public class WithdrawDepositActivity extends BaseActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.titletext)
    TextView titletext;
    @BindView(R.id.money_tixian)
    TextView moneyTixian;
    @BindView(R.id.bankAccount)
    TextView bankAccount;
    @BindView(R.id.nocard)
    TextView noCard;
    @BindView(R.id.cardType)
    TextView cardType;
    @BindView(R.id.bankL)
    AutoRelativeLayout bankL;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.tixian)
    Button tixian;
    @BindView(R.id.error_layout)
    EmptyLayout mEmptyLayout;
    double money;
    double txMoney;
    String userId;
    int bankId = -1;
    View layout;
    PayPwdEditText payPwdEditText;
    String pw;
    Dialog dialog;
    int orientation;
    Button negativeBt;
    boolean payPwdIfSet = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //注册
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //againData();
        initData();
    }

    @Override
    public void initView() {
        money = Double.parseDouble(getIntent().getStringExtra("money"));
        moneyTixian.setText("￥ "+NetUtils.setDecimal(money));
        LayoutInflater inflater = getLayoutInflater();
        layout = inflater.inflate(R.layout.dialog_paypwd2, (ViewGroup) findViewById(R.id.dialog_paypwd));
        negativeBt = (Button) layout.findViewById(R.id.negative);
        //gpw = (GridPasswordView) layout.findViewById(R.id.gpv_tx);
        payPwdEditText = (PayPwdEditText) layout.findViewById(R.id.gpv_tx);
        titletext.setText("提现申请");

        /**
         * @param bgdrawable 背景drawable
         * @param pwdlength 密码长度
         * @param splilinewidth 分割线宽度
         * @param splilinecolor 分割线颜色
         * @param pwdcolor 密码字体颜色
         * @param pwdsize 密码字体大小
         */
        payPwdEditText.initStyle(R.drawable.edit_num_bg, 6, 0.5f, R.color.black, R.color.black, 20);
        payPwdEditText.setOnTextFinishListener(new PayPwdEditText.OnTextFinishListener() {
            @Override
            public void onFinish(String str) {//密码输入完后的回调
                if (!NetUtils.isConnected(WithdrawDepositActivity.this)) {
                    Toast.makeText(WithdrawDepositActivity.this, "请检查你的网络", Toast.LENGTH_SHORT).show();
                } else {
                    mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                    OkUtilCallback callback = new OkUtilCallback(mEmptyLayout) {
                        @Override
                        public void onMyResponse(String response, int id) {
                            Gson gson = new Gson();
                            Entity card = gson.fromJson(response, Entity.class);
                            if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                                BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                payPwdEditText.clearText();
                            } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                                BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                //BaseApplication.getIntstance().showToast("提现成功", Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                txMoney = Double.parseDouble(etMoney.getText().toString());//提现多少
                                String a = moneyTixian.getText().toString();//可提现金额
                                String b = a.substring(2, a.length());
                                money = Double.parseDouble(b);
                                moneyTixian.setText("￥ "+(money-txMoney));
                                /*Intent intent1 = new Intent();
                                intent1.putExtra("money",moneyTixian.getText().toString());
                                setResult(505,intent1);*/
                                etMoney.setText("");
                                dialog.dismiss();
                            }
                        }
                    };
                    /*会员提现
                    userId int[Y] 会员ID
                    amount double[Y]
                    bankId int [Y] 绑定的银行或者支付宝ID
                    payPwd  string[Y] 支付密码*/
                    pw = payPwdEditText.getPwdText();
                    OKUtilAPI.post(OKUtilAPI.tixian, "userId=" + userId + "&bankId=" + bankId + "&amount=" + txMoney + "&payPwd="+pw, callback);
                }
            }
        });

        //输入两位小数，而且“.”不在开头和结尾，不能输都是0
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                /*if(s == null || s.length() == 0){

                }
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        etMoney.setText(s);
                        etMoney.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    etMoney.setText(s);
                    etMoney.setSelection(2);
                }

                if (s.toString().startsWith("0")&& s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        etMoney.setText(s.subSequence(0, 1));
                        etMoney.setSelection(1);
                        return;
                    }
                }*/
            }

            @Override
            public void afterTextChanged(Editable editable) {
                //控制开头不为0
                String text = editable.toString();
                int len = text.length();
                if (len==1&&text.equals("0")){
                    editable.clear();
                }
            }
        });
    }

    @Override
    public void initData() {
        userId = SPUtils.getStringData(this, SPUtils.USERID);
        if (!NetUtils.isConnected(this)) {
            Toast.makeText(this, "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            OkUtilCallback callback1 = new OkUtilCallback(mEmptyLayout) {
                @Override
                public void onMyResponse(String response, int id) {
                    Gson gson = new Gson();
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response);
                        if ("OK".equals(jsonObject.getString("result"))) {
                            if (!jsonObject.isNull("bank")) {
                                DefaultBank card = gson.fromJson(response, DefaultBank.class);
                                if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult())) && card.getLogin()) {
                                    BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                                    BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                                } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                                    DefaultBank.BankBean bank = card.getBank();
                                    noCard.setVisibility(View.GONE);
                                    boolean a = false;
                                    if (bankId!=-1){
                                        a = true;
                                    }
                                    //如果bankId不存在，
                                    if (!a) {
                                        String c = bank.getCardType();
                                        if ("".equals(c)) {
                                            cardType.setText("支付宝");
                                        } else {
                                            cardType.setText(c);
                                        }
                                        String d = bank.getBankAccount();
                                        String b = d.substring(d.length() - 4, d.length());
                                        bankAccount.setText("尾号" + b);
                                        bankId = bank.getId();
                                    }
                                }
                            }
                            else {
                                getAllBank();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            };
            //获取默认银行/支付宝的信息,userId  int[Y] 会员ID
            OKUtilAPI.post(OKUtilAPI.defaultBank, "userId=" + userId, callback1);

            final OkUtilCallback okUtilCallback = new OkUtilCallback(){
                @Override
                public void onMyResponse(String response, int id) {
                    UserData entity = gson.fromJson(response,UserData.class);
                    if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))&&entity.getLogin()){
                        mEmptyLayout.setErrorType(EmptyLayout.NO_LOGIN);
                    }else if((!AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                        BaseApplication.getIntstance().showToast(entity.getResult(), Toast.LENGTH_SHORT,0, Gravity.TOP);
                    }else if((AppConfig.RESULT_OK.equalsIgnoreCase(entity.getResult()))){
                        payPwdIfSet = entity.isPayPwdIfSet();
                    }
                }
            };
            OKUtilAPI.post(OKUtilAPI.getUser, "userId=" + userId , okUtilCallback);
        }
    }

    public void  getAllBank(){
        userId = SPUtils.getStringData(this, SPUtils.USERID);
        if (!NetUtils.isConnected(this)) {
            Toast.makeText(this, "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            OkUtilCallback callback = new OkUtilCallback(mEmptyLayout) {
                @Override
                public void onMyResponse(String response, int id) {
                    Gson gson = new Gson();
                    AllCard card = gson.fromJson(response, AllCard.class);
                    if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                        BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                    } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                        List<AllCard.ListBean> list = card.getList();
                        if (null == list || list.size() == 0) {
                            noCard.setVisibility(View.VISIBLE);
                            bankAccount.setText("");
                            cardType.setText("");
                        } else {
                            noCard.setVisibility(View.GONE);
                            boolean a = false;
                            for (int i = 0;i<list.size();i++){
                                //判断bankId是否存在，即判断是否选择了某一银行卡或支付宝
                                if(list.get(i).getId()==bankId){
                                    a = true;
                                }
                            }
                            //如果bankId不存在，
                            if (!a){
                                String c = card.getList().get(0).getCardType();
                                if ("".equals(c)){
                                    cardType.setText("支付宝");
                                }else {
                                    cardType.setText(c);
                                }
                                String d = card.getList().get(0).getBankAccount();
                                String b = d.substring(d.length() - 4, d.length());
                                bankAccount.setText("尾号" + b);
                                bankId = card.getList().get(0).getId();
                            }
                        }
                    }
                }
            };
            //查看绑定卡列表,type  int[N]  1:查看银行卡 2:查看支付宝 查看全部
            OKUtilAPI.post(OKUtilAPI.getCard, "userId=" + userId + "&type=", callback);
        }
    }
    public void againData(){
        userId = SPUtils.getStringData(this, SPUtils.USERID);
        if (!NetUtils.isConnected(this)) {
            Toast.makeText(this, "请检查你的网络", Toast.LENGTH_SHORT).show();
        } else {
            mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            OkUtilCallback callback = new OkUtilCallback(mEmptyLayout) {
                @Override
                public void onMyResponse(String response, int id) {
                    Gson gson = new Gson();
                    AllCard card = gson.fromJson(response, AllCard.class);
                    if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult())) && card.getLogin()) {
                        BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                    } else if ((!AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                        BaseApplication.getIntstance().showToast(card.getResult(), Toast.LENGTH_SHORT, 0, Gravity.TOP);
                    } else if ((AppConfig.RESULT_OK.equalsIgnoreCase(card.getResult()))) {
                        List<AllCard.ListBean> list = card.getList();
                        if (null == list || list.size() == 0) {
                            noCard.setVisibility(View.VISIBLE);
                            bankAccount.setText("");
                            cardType.setText("");
                        }else {
                            noCard.setVisibility(View.GONE);
                            boolean a = false;
                            for (int i = 0;i<list.size();i++){
                                if(list.get(i).getId()==bankId){
                                    a = true;
                                }
                            }
                            if (!a){
                                String c = list.get(0).getCardType();
                                if ("".equals(c)){
                                    cardType.setText("支付宝");
                                }else {
                                    cardType.setText(c);
                                }
                                String d = list.get(0).getBankAccount();
                                String b = d.substring(d.length() - 4, d.length());
                                bankAccount.setText("尾号" + b);
                                bankId = card.getList().get(0).getId();
                            }
                        }
                    }
                }
            };
            //查看绑定卡列表,type  int[N]  1:查看银行卡 2:查看支付宝 查看全部
            OKUtilAPI.post(OKUtilAPI.getCard, "userId=" + userId + "&type=", callback);
        }
    }


    @Override
    public int getContentViewId() {
        return R.layout.activity_withdraw_deposit;
    }

    @Override
    protected String getFragmentTag() {
        return null;
    }

    @OnClick({R.id.bankL,R.id.tixian,R.id.back})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.bankL :
                Intent intent = new Intent(this, BindSettingActivity.class);
                startActivity(intent);
                bankId = -1;
                break;

            case R.id.tixian :
                txMoney = Double.parseDouble(etMoney.getText().toString());
                if ("".equals(etMoney.getText().toString())||txMoney == 0){
                    BaseApplication.getIntstance().showToast("请输入提现金额", Toast.LENGTH_SHORT, 0, Gravity.TOP);
                }else if (bankId==-1){
                    BaseApplication.getIntstance().showToast("请绑定银行卡或支付宝", Toast.LENGTH_SHORT, 0, Gravity.TOP);
                }else if (txMoney>money){
                    BaseApplication.getIntstance().showToast("金额不足", Toast.LENGTH_SHORT, 0, Gravity.TOP);
                }else if (!payPwdIfSet){
                    BaseApplication.showToast(R.string.no_pay_pwd);
                }else {
                    if(dialog == null){
                        dialog = new Dialog(this, R.style.FullScreenDialog);
                        dialog.setContentView(layout);
                        negativeBt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                payPwdEditText.clearText();
                            }
                        });
                        WindowManager m = getWindowManager();
                        Window dialogWindow = dialog.getWindow();
                        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
                        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
                        orientation = getResources().getConfiguration().orientation;
                        if (orientation==0||orientation==2){
                            p.height = (int) (d.getHeight() * 0.43); // 高度设置为屏幕的0.5
                            p.width = (int) (d.getWidth() * 0.4); // 宽度设置为屏幕的0.4
                        }else {
                            p.height = (int) (d.getHeight() * 0.4); // 高度设置为屏幕的0.6
                            p.width = (int) (d.getWidth() * 0.8); // 宽度设置为屏幕的0.65
                        }
                        dialogWindow.setAttributes(p);
                        dialog.show();
                    }else {
                        payPwdEditText.clearText();
                        dialog.show();
                    }
                }
                break;
            case R.id.back :
                finish();
                break;
        }
    }

    public void onEventMainThread(Bundle bundle) {
        if ("bindBankFragment".equals(bundle.getString("from"))){
            bankId = bundle.getInt("id");
            bundle.getString("account");
            bundle.getString("cardType");
            String a = bundle.getString("account");
            String b = a.substring(a.length() - 4, a.length());
            bankAccount.setText("尾号" + b);
            cardType.setText(bundle.getString("cardType"));
            noCard.setVisibility(View.GONE);

        }else if ("bindAlipayFragment".equals(bundle.getString("from"))){
            bankId = bundle.getInt("id");
            bundle.getString("account");
            String a = bundle.getString("account");
            String b = a.substring(a.length() - 4, a.length());
            bankAccount.setText("尾号" + b);
            cardType.setText("支付宝");
            noCard.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
